from flask import Blueprint, request, jsonify
from app.models.garbage_knowledge import GarbageKnowledge

knowledge_bp = Blueprint('knowledge_bp', __name__)

dic = {
    0: "可回收物",
    1: "有害垃圾",
    2: "厨余垃圾",
    3: "其他垃圾"
}


@knowledge_bp.route('/api/knowledge', methods=['GET'])
def get_knowledge_by_category():
    page = request.args.get("page", 1, type=int)  # 页码，默认第 1 页
    category = request.args.get("category", 1, type=int)
    category_name = dic[category]

    if not category_name:
        return jsonify({'code': 400, 'msg': '无效的分类名称'}), 400

    pagination = GarbageKnowledge.query.filter_by(category=category_name).paginate(
        page=page, per_page=20, error_out=False
    )
    items = [item.to_dict() for item in pagination.items]

    return jsonify({
        'code': 200,
        'msg': 'success',
        'data': {
            'items': items,
            'hasMore': pagination.page < pagination.pages,
        }
    })


@knowledge_bp.route('/api/knowledge/search', methods=['GET'])
def search_knowledge():
    keyword = request.args.get('kw', '')
    if not keyword:
        return jsonify({'code': 400, 'msg': '缺少搜索关键词'}), 400

    results = GarbageKnowledge.search_by_keyword(keyword)
    CATEGORY_MAP = {
        "可回收物": 0,
        "有害垃圾": 1,
        "厨余垃圾": 2,
        "其他垃圾": 3
    }

    data = []
    for item in results:
        item_dict = item.to_dict()
        # 替换 category
        if item_dict.get("lajitype") in CATEGORY_MAP:
            item_dict["lajitype"] = CATEGORY_MAP[item_dict["lajitype"]]
        else:
            item_dict["lajitype"] = 5  # 未知类型
        data.append(item_dict)

    return jsonify({
        'code': 200,
        'msg': 'success',
        'data': data
    })
